package com.ciwong.epaper.modules.me.ui;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpagerErrcode;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.bean.HideDownloadDialogBean;
import com.ciwong.epaper.common.CheckIsExamForDetail;
import com.ciwong.epaper.common.guidedialog.ChooseReadDialog;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.epaper.bean.BasePaging;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.dao.EpaperRequest;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.HomeWorkUtil;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.evaluate.ui.SpeechPlayController;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.modules.interactivetutorial.InteractiveTutorialCordovaActivity;
import com.ciwong.epaper.modules.me.adapter.HomeWorkAdapter;
import com.ciwong.epaper.modules.me.bean.CheckValidBean;
import com.ciwong.epaper.modules.me.bean.MenuOptionBean;
import com.ciwong.epaper.modules.me.bean.MyWork;
import com.ciwong.epaper.modules.me.bean.RequirementContent;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.onlineanswer.OnlineAnswerCordovaActivity;
import com.ciwong.epaper.modules.scan.bean.EpaperQRInfo;
import com.ciwong.epaper.modules.viedoexplantion.util.ViedoJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.EJumpManager;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadDB;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.epaper.widget.HomeWorkHintDialog;
import com.ciwong.epaper.widget.NewBottomMenuDialog;
import com.ciwong.epaper.widget.PullToRefreshView;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.bean.Main;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.DownloadProgressBar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by wen  on 2018/2/1.
 * <p>
 * 历史作业页面
 */

public class EarlierHomeWorkActivity extends BaseActivity
        implements PullToRefreshView.OnHeaderRefreshListener,
        PullToRefreshView.OnFooterRefreshListener,
        ExpandableListView.OnGroupClickListener,
        ExpandableListView.OnChildClickListener {
    /**
     * 可扩展ListView
     */
    private ExpandableListView expandableListView;
    /**
     * 数据集合
     */
    public List<MyWork> myWorks = new ArrayList<MyWork>();
    /**
     * 数据适配器
     */
    public HomeWorkAdapter mHomeWorkAdapter;

    /**
     * 是否是刷新状态,true为刷新，false为加载更多
     */
    private boolean isRefresh = true;
    /**
     * 默认从第一页开始加载
     */
    private final int defult_page = 1;
    /**
     * 当前页码
     */
    private int curPage = defult_page;

    /**
     * 默认加载数据大小
     */
    private static final int LOAD_PAGE_SIZE = 20;
    /**
     * 为互动教程做作业回来时 做延时加载
     */
    private static final int DELAY_TIME_INTERACTIVE_TUTORIAL = 2000;


    /**
     * 刷新ListView
     */
    private PullToRefreshView my_work_refresh_view;
    private LinearLayout mLayoutData, mLayoutEmpty, mLayoutNetError;
    private ImageView mIvEmpty;
    private TextView mTvEmptyTips, mTvEmptyTips2;

    private Handler handler = new Handler();

    private NewBottomMenuDialog bottomMenuDialog;

    private MyWork mCurrentMyWork;
    private WorkContents mCurrentWorkContents;
    public int selectedGroupPosition = -1;
    public int selectedChildPosition = -1;

    private DownLoadInfo mCurrentDownloadInfo;
    private boolean isNoMoreData = false;
    private int mPageCount = -1;
    private Button mBtnTryAgain;


    @Override
    protected int setView() {
        return R.layout.hasdonehomework;

    }

    @Override
    protected void findViews() {
        expandableListView = findViewById(R.id.my_done_work_exlistv);
        my_work_refresh_view = findViewById(R.id.my_done_work_refresh_view);
        mLayoutData = findViewById(R.id.ll_data_show_layout);
        mLayoutEmpty = findViewById(R.id.ll_has_done_empty_layout);
        mLayoutNetError = findViewById(R.id.ll_network_error);
        mBtnTryAgain = findViewById(R.id.btn_try_again);
        mTvEmptyTips = findViewById(R.id.tv_empty_tips);
        mTvEmptyTips2 = findViewById(R.id.tv_empty_tips2);
        mIvEmpty = findViewById(R.id.iv_emtpy);


    }

    @Override
    protected void initEvent() {
        expandableListView.setOnGroupClickListener(this);
        expandableListView.setOnChildClickListener(this);
        my_work_refresh_view.setOnHeaderRefreshListener(this);
        my_work_refresh_view.setOnFooterRefreshListener(this);
        setDownloadProgressOnDismissListener(new DownloadProgressBar.OnDownLoadDialogDismissListener() {
            @Override
            public void ondDismiss(DownloadProgressBar downloadProgressBar) {
                try {
                    if (mCurrentDownloadInfo != null) {
                        int status = mCurrentDownloadInfo.getStatus();
                        if (status == DownloadStatus.STATUS_LOADING || status == DownloadStatus.STATUS_DOWNLOADING) {
                            DownLoad.getInstance().pauseTask(mCurrentDownloadInfo);
                        }

                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        });
        mBtnTryAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetworkUtils.isOnline()) {
                    refreshNetData(true);
                }
            }
        });

    }

    @Override
    protected void init() {
        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }
        EventBus.getDefault().register(this);
        registerBoradcastReceiver();

    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG);
        myIntentFilter.addAction(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG);
        myIntentFilter.addAction(EpaperConstant.INTENT_BOACK_REF_WORK);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            if (EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG.equals(intent.getAction())) {

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshNetData(true);
                    }
                }, DELAY_TIME_INTERACTIVE_TUTORIAL);

            } else if (EpaperConstant.BROADCAST_HOME_WORK_STATUS_INTERACTIVE_TUTORIAL_FINASH.equals(intent.getAction())) {
                //专门为互动教程 延时请求处理

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshNetData(true);
                    }
                }, DELAY_TIME_INTERACTIVE_TUTORIAL);


            } else if (EpaperConstant.INTENT_BOACK_REF_WORK.equals(intent.getAction())) {
                if (selectedChildPosition > -1 && selectedGroupPosition > -1) {
                    try {
                        float actual_score = intent.getFloatExtra(IntentFlag.INTENT_FLAG_ACTUAL_SCORE, 0);
                        int workStatus = intent.getIntExtra(IntentFlag.INTENT_FLAG_WORK_STATUS, 0);
                        WorkContents workContents = myWorks.get(selectedGroupPosition).getWorkContents().get(selectedChildPosition);
                        if (workStatus == 16) {//听说模考显示评分中
                            workContents.setWorkStatus(16);
                        } else if (workStatus == 17) {//在线作答有主观题显示下划线。
                            workContents.setWorkStatus(17);
                        } else {
                            workContents.setSubmitCount(workContents.getSubmitCount());
                            workContents.setShowScore(actual_score + "");
                            mHomeWorkAdapter.notifyDataSetChanged();
                        }
                    } catch (IndexOutOfBoundsException e) {

                    } catch (Exception e) {

                    }
                }
                selectedGroupPosition = -1;
                selectedChildPosition = -1;
                refreshNetData(true);
            }
        }
    };


    @Override
    protected void loadData() {
        setTitleText("全部未完成作业");
        loadLocalData();
        mHomeWorkAdapter = new HomeWorkAdapter(EarlierHomeWorkActivity.this, myWorks, 0, false);
        expandableListView.setAdapter(mHomeWorkAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }
    }

    @Override
    public void onStop() {
        if (EventBus.getDownLoadInstance().isRegistered(this) && !isTopActivity()) {
            EventBus.getDownLoadInstance().unregister(this);
            hideDownloadProgress();
        }
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().unregister(this);
        }
        EventBus.getDefault().unregister(this);
        if (mBroadcastReceiver != null) {
            unregisterReceiver(mBroadcastReceiver);
        }
    }

    /**
     * 添加本地数据
     */
    private void loadLocalData() {
        this.showCricleProgress();
        SerializableManager.getInstance().deSerialize(
                SerializableManager.SerializeKey.SHARE_KEY_EARLIER_NOTIFICATION_LIST,
                new BaseCallBack() {
                    @Override
                    public void success(Object data) {
                        if (data != null) {
                            List<MyWork> list = (List<MyWork>) data;
                            myWorks.clear();
                            myWorks.addAll(list);
                            refreshUI();
                        }
                        hideCricleProgress();
                        refreshNetData(true);
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        if (NetworkUtils.isOnline()) {
                            refreshNetData(true);
                        } else {
                            hideCricleProgress();
                            showNetErrorView();
                        }

                    }

                    @Override
                    public void failed(Object data) {
                        if (NetworkUtils.isOnline()) {
                            refreshNetData(true);
                        } else {
                            hideCricleProgress();
                            showNetErrorView();
                        }
                    }
                });
    }

    /**
     * 刷新网络数据(true为刷新，false为添加更多)
     *
     * @param boo
     */
    public void refreshNetData(boolean boo) {
        isRefresh = boo;
        if (isRefresh) {
            curPage = defult_page;
        }
        getMyWorkList();
    }

    /**
     * 获取作业通知列表
     */
    private void getMyWorkList() {

        if (null == EApplication.getInstance().getUserInfoBase()) {
            return;
        }
        EpaperDao.getInstance().getMyWork(EApplication.BRAND_ID, 0, curPage,
                LOAD_PAGE_SIZE, 3, false, false, new BaseExtCallBack(EarlierHomeWorkActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                    @Override
                    public void success(Object data) {
                        try {
                            hideCricleProgress();
                            BasePaging<MyWork> workNotifyBasePaging = (BasePaging<MyWork>) data;
                            CopyOnWriteArrayList<MyWork> list = new CopyOnWriteArrayList<MyWork>(
                                    workNotifyBasePaging.getPageList());
                            mPageCount = workNotifyBasePaging.getPageCount();
                            if (list != null) {
                                // 过滤掉未做过但已被撤销了的作业
                                for (Iterator iterator = list.iterator(); iterator.hasNext(); ) {
                                    MyWork myWork = (MyWork) iterator.next();
                                    if (myWork.getIsDel() == 1) {// 已撤销 已删除
                                        list.remove(myWork);
                                    }
                                }
                                refreshListData(list);
                                if (((list.size() == 0 || curPage > mPageCount) && !isRefresh)
                                        || mPageCount == 1 || mPageCount == 0) {
                                    isNoMoreData = true;
                                } else {
                                    isNoMoreData = false;
                                }
                                getDownloadingTaskAndRefresh(list);
                                refreshUI();
                            }
                            loadOver();
                        } catch (Exception e) {
                            e.getStackTrace();
                        }
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        failed(data);
                    }

                    @Override
                    public void failed(Object data) {
                        hideCricleProgress();
                        if (data instanceof AuthFailureError) {
                            EJumpManager.jumpToDialogActivity(EarlierHomeWorkActivity.this);
                        } else if (EpagerErrcode.VOLLERY_AUTHENTICATION_I0EXCEPTION.equals(data.toString())) { //token 失效，volley 处理异常
                            EJumpManager.jumpToDialogActivity(EarlierHomeWorkActivity.this);
                        } else if (!NetworkUtils.isOnline()) {
                            ToastUtil.INSTANCE.toastCenterNoNetError();
                        } else {

                        }
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HASDONE__HOMEWORK_LIST, data == null ? "" : "失败信息：" + data.toString(), "获取更早作业失败" + getUrl(), true);


                        loadOver();
                    }
                });

    }

    /**
     * 刷新UI
     */
    private void refreshUI() {
        mHomeWorkAdapter.notifyDataSetChanged();
        showNormalView();
        my_work_refresh_view.setVisibility(View.VISIBLE);
        for (int i = 0; i < mHomeWorkAdapter.getGroupCount(); i++) {
            expandableListView.expandGroup(i);
        }
        if (myWorks.isEmpty()) {
//            my_work_refresh_view.setEnablePullLoadMoreDataStatus(false);
            showEmptyView();
        } else {
            if (isRefresh) {
                my_work_refresh_view.setEnablePullLoadMoreDataStatus(true);// 设置启动加载更多
            }
        }
    }

    private void showEmptyView() {
        mIvEmpty.setImageResource(R.mipmap.icon_homework_completed);
        mTvEmptyTips.setText(R.string.homework_compelted);
        mTvEmptyTips2.setVisibility(View.GONE);
        mLayoutEmpty.setVisibility(View.VISIBLE);
        mLayoutData.setVisibility(View.GONE);
        mLayoutEmpty.setVisibility(View.VISIBLE);
        mLayoutNetError.setVisibility(View.GONE);
    }

    private void showNormalView() {
        mLayoutData.setVisibility(View.VISIBLE);
        mLayoutEmpty.setVisibility(View.GONE);
        mLayoutNetError.setVisibility(View.GONE);
    }

    private void showNetErrorView() {
        mLayoutData.setVisibility(View.GONE);
        mLayoutEmpty.setVisibility(View.GONE);
        mLayoutNetError.setVisibility(View.VISIBLE);
    }

    /**
     * 加载完成
     */
    private void loadOver() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isRefresh) {
                    if (isNoMoreData) {
                        my_work_refresh_view.onHeaderRefreshComplete();
                        my_work_refresh_view.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
                    } else {
                        my_work_refresh_view.onHeaderRefreshComplete();
                    }
                } else {
                    if (isNoMoreData) {
                        my_work_refresh_view.onFooterRefreshComplete();
                        my_work_refresh_view.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
                    } else {
                        my_work_refresh_view.onFooterRefreshComplete();
                    }
                }
            }
        }, 500);

    }


    /**
     * 匹配刷新下载状态
     *
     * @param myWorksList
     */
    private void getDownloadingTaskAndRefresh(final List<MyWork> myWorksList) {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                List<DownLoadInfo> downLoadInfoList = DownLoadDB
                        .queryUnCompletedList();
                if (downLoadInfoList != null && !downLoadInfoList.isEmpty()) {
                    for (Iterator iterator = myWorksList.iterator(); iterator
                            .hasNext(); ) {
                        MyWork myWork = (MyWork) iterator.next();

                        List<WorkContents> workContentsList = myWork
                                .getWorkContents();

                        for (Iterator iterator1 = workContentsList
                                .iterator(); iterator1.hasNext(); ) {
                            WorkContents tempWorkContent = (WorkContents) iterator1.next();

                            DownLoadInfo tempInfo = new DownLoadInfo();
                            tempInfo.setIsEqualsWork(true);
                            tempInfo.setBookId(tempWorkContent.getPackageId());
                            tempInfo.setChapterId(tempWorkContent.getcId());
                            int index = downLoadInfoList.indexOf(tempInfo);
                            if (index != -1) {
                                DownLoadInfo info = downLoadInfoList.get(index);
                                if (tempWorkContent.getcId()
                                        .equals(info.getChapterId())
                                        && tempWorkContent.getPackageId()
                                        .equals(info.getBookId())) {
                                    tempWorkContent.setDownloadStatus(
                                            info.getStatus());
                                }
                            }
                        }
                    }

                }
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    /**
     * 刷新数据
     *
     * @param list 列表
     */
    private void refreshListData(List<MyWork> list) {
        if (isRefresh) {
            myWorks.clear();
        }
        curPage++;// 请求下一页
        myWorks.addAll(list);
        //refreshUI();
        if (isRefresh) {
            // 保存本地数据
            SerializableManager.getInstance().serialize(
                    SerializableManager.SerializeKey.SHARE_KEY_EARLIER_NOTIFICATION_LIST,
                    (Serializable) myWorks);
        }
    }


    private AdapterView.OnItemClickListener bgOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {

                case 0:// 再次跟读
                    initJumpToParam(mCurrentMyWork, mCurrentWorkContents, selectedGroupPosition, selectedChildPosition);
                    break;
                case 1:// 排行榜
                    MeJumpManager.jumpToRankH5Activity(R.string.go_back, EarlierHomeWorkActivity.this, mCurrentWorkContents.contentId + "", mCurrentWorkContents.getResourceName());

                    break;

                default:
                    break;
            }

            if (null != bottomMenuDialog && bottomMenuDialog.isShowing()) {
                bottomMenuDialog.dismiss();
            }
        }
    };

    public void showMoreDialogMenu(final MyWork myWork, final WorkContents workContents, final int groupPosition, final int childPosition) {
        //跳转排行榜
        MeJumpManager.jumpToRankH5Activity(R.string.go_back, EarlierHomeWorkActivity.this, workContents.contentId + "", workContents.getResourceName());

    }

    private void jumpToNewStudyRecordH5(WorkContents workContent) {
        String url = "";
        String pageType = "0";
        if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
            url = EpaperConstant.URL_LSW_DETAILS;
        } else if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT || workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_SENTENCE_REPEAT) {
            if (workContent.getResourceType().equals(ModuleContent.ResourceType.RESOURCE_TYPE_WORD)) {
                pageType = "1";
            } else {
                pageType = "3";
            }
            url = EpaperConstant.URL_READING_REPEAD + "pageType=" + pageType + "&parentVersionId=" + workContent.parentVersionId;
        } else if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {//在线作答
            pageType = "1";
            url = EpaperConstant.URL_ONLINE_PAPER_DETAIL_H5 + "pageType=" + pageType;
        } else if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_INTERACTIVE_TUTORIAL) {//互动教程
            pageType = "1";
            url = EpaperConstant.URL_INTERACTIVE_TUTORIAL_DETAIL_H5 + "pageType=" + pageType;
        }
        StringBuffer sb = new StringBuffer(url);
        sb.append("&clientId=");
        sb.append(EConstants.CLIENT_ID);
        long userId = EApplication.getInstance().getUserInfoBase().getUserId();
        sb.append("&userId=");
        sb.append(userId);
        sb.append("&brandId=");
        sb.append(EApplication.BRAND_ID);
        sb.append("&versionId=");
        sb.append(workContent.getVersionId());
        sb.append("&doWorkId=");
        sb.append(workContent.getDoWorkId());
        if (url.equals(EpaperConstant.URL_LSW_DETAILS)) {
            sb.append("&revisedMode=1");
        }
        String title;
        try {
            title = java.net.URLEncoder.encode(workContent.getResourceName(), "UTF-8");

        } catch (UnsupportedEncodingException e) {
            title = "";
        }
        title = title.replace("+", "%20");
        sb.append("&title=");
        sb.append(title);
        sb.append("&doWorkType=0");
        MeJumpManager.jumpToStudyRecordH5Activity(ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT, EarlierHomeWorkActivity.this, R.string.go_back, -1, sb.toString(), workContent.getResourceName(), 0);
    }


    @Override
    public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
        showDownloadProgress("玩命加载中,请耐心等待......");
        mCurrentMyWork = myWorks.get(i);
        mCurrentWorkContents = mCurrentMyWork.getWorkContents().get(i1);
        this.selectedGroupPosition = i;
        this.selectedChildPosition = i1;
        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
            hideDownloadProgress();
            return false;
        }
        int requireReadTimes = 1;
        String str_requirementContent = mCurrentWorkContents.requirementContent;
        if ((mCurrentWorkContents.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT || mCurrentWorkContents.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_SENTENCE_REPEAT) && !TextUtils.isEmpty(str_requirementContent)) {
            RequirementContent requirementContent = new Gson().fromJson(str_requirementContent,
                    RequirementContent.class);
            requireReadTimes = requirementContent.getReadtimes();
        }

        if (((mCurrentWorkContents.getModuleId() != ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT && mCurrentWorkContents.getModuleId() != ModuleInfo.ModuleInfoId.MODULE_ID_SENTENCE_REPEAT) && mCurrentWorkContents.getSubmitCount() > 0)
                || ((mCurrentWorkContents.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT || mCurrentWorkContents.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_SENTENCE_REPEAT) && mCurrentWorkContents.getSubmitCount() >= requireReadTimes)) { // 有提交记录,将会跳转到学习记录
            hideDownloadProgress();
            jumpToNewStudyRecordH5(mCurrentWorkContents);

        } else {//没有提交记录，将会进入做作业界面
            initJumpToParam(mCurrentMyWork, mCurrentWorkContents, i, i1);
        }

        return false;
    }

    /**
     * @param myWork
     * @param workContent
     * @param groupPosition
     * @param childPosition
     */
    public void initJumpToParam(final MyWork myWork, final WorkContents workContent, final int groupPosition, final int childPosition) {

        try {
            showDownloadProgress();
            if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN || workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN_NEW) {
                //视频讲解点播视频再判断
                validSuccess(workContent, groupPosition, childPosition, myWork);
            } else if (workContent.workTag == ModuleInfo.ModuleInfoId.WORK_TAG_EXAM) {//试卷
                MeJumpManager.jumpToExamCordovaActivity(EarlierHomeWorkActivity.this, OnlineAnswerCordovaActivity.FROM_HOME_WORK, myWork.getWorkId(), myWork.getServiceType(), workContent, 1, myWork.getEffectiveDate());
                hideCricleProgress();

            } else {
                EpaperRequest.checkValid(EApplication.BRAND_ID + "", myWork.getServiceType() + "", workContent.getPackageId(), workContent.getcId(), null, new BaseExtCallBack(EarlierHomeWorkActivity.this) {
                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        hideDownloadProgress();
                        if (errorCode == 5201) {
                            ToastUtil.INSTANCE.toastCenterErrorWithErrorCode(data.toString(), errorCode);
                        } else {
                            if (null != data && errorCode != 17 && errorCode != 27) {
                                ToastUtil.INSTANCE.toastCenterNoNetErrorOrServerError();
                            }
                        }

                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_EARLIER_HOMEWORK_LIST, data == null ? "" : "失败信息：" + data.toString(), "检查权限失败" + getUrl(), true);


                    }

                    @Override
                    public void failed(Object data) {
                        ToastUtil.INSTANCE.toastCenterError(R.string.server_error);

                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_EARLIER_HOMEWORK_LIST, data == null ? "" : "失败信息：" + data.toString(), "检查权限失败" + getUrl(), true);
                        hideDownloadProgress();
                    }

                    @Override
                    public void success(Object data) {
                        if (data == null) {
                            ToastUtil.INSTANCE.toastCenterError("检查权限失败!");
                            hideDownloadProgress();
                        } else {
                            CheckValidBean checkValidBean = (CheckValidBean) data;
                            if (checkValidBean != null && checkValidBean.isValid == 1) { //有权限
                                validSuccess(workContent, groupPosition, childPosition, myWork);
                            } else {//没有权限
                                MeJumpManager.jumpBuyService(EarlierHomeWorkActivity.this, R.string.go_back, myWork.getServiceType(), -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, checkValidBean.msg);
                                hideDownloadProgress();
                            }
                        }
                    }
                });


            }
        } catch (Exception e) {
            hideDownloadProgress();
            e.getStackTrace();
        }


    }


    /**
     * 判断权限成功
     *
     * @param workContent
     * @param groupPosition
     * @param childPosition
     * @param myWork
     */
    private void validSuccess(WorkContents workContent, int groupPosition, int childPosition, MyWork myWork) {
        try {
            //        if (TextUtils.isEmpty(workContent.resourceUrl)) {//旧的资源

            DownLoadInfo downLoadInfoNew = DownLoad.getInstance().isPackageExist_New(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId());
            DownLoadInfo downLoadInfo = DownLoad.getInstance().isPackageExist(workContent.getPackageId(), workContent.getcId());
            String mainJsonPath = ESystem.getPackagesMainJsonPath(workContent.getPackageId(), workContent.getcId());
            String catalogueJsonPath = ESystem.getPackagesCatalogueJsonPath(workContent.getPackageId(), workContent.getcId());
            String resourcePath = ESystem.getPackagesResourcePath(workContent.getPackageId(), workContent.getcId());
            //资源不存在,而且本地也没有，就去下载了
            if (downLoadInfoNew == null && downLoadInfo == null) {
                downLoadWork(workContent, groupPosition, childPosition);
            } else {
                if (downLoadInfoNew != null) {
                    //新资源
                    File packagesCatalogueFile_New = new File(ESystem.getPackagesCatalogueNew(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId()));
                    File packagesCatalogueMediaFile_New = new File(ESystem.getPackagesMediaPath_New(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId()));

                    File packagesCatalogueResourceFile_New = new File(ESystem.getPackagesResourcePath_New(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId()));
                    if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER || workContent.workTag == 2) {//线上作答和试卷不验证media文件夹
                        if (packagesCatalogueFile_New.exists() && packagesCatalogueResourceFile_New.exists()
                                && packagesCatalogueResourceFile_New.list().length > 0) {//lzh添加此处判断，解决资源文件内容被删除后打不开) {
                            hideDownloadProgress();
                            jumpToWork(workContent, downLoadInfoNew, myWork);
                        } else {//没有下载过，或者有部分文件被勿删过。
                            downLoadWork(workContent, groupPosition, childPosition);
                        }
                    } else {//其他作业需要验证media文件夹

                        if (packagesCatalogueFile_New.exists() && packagesCatalogueMediaFile_New.exists() && packagesCatalogueResourceFile_New.exists()
                                && packagesCatalogueResourceFile_New.list().length > 0) {//lzh添加此处判断，解决资源文件内容被删除后打不开
                            if (!ListenSpeakUtil.isOnLineAnswerOrListenSpeakOrInteractiveTutorial(workContent.getModuleId())) {
                                hideDownloadProgress();
                            }
                            jumpToWork(workContent, downLoadInfoNew, myWork);
                        } else {//没有下载过，或者有部分文件被勿删过。
                            downLoadWork(workContent, groupPosition, childPosition);
                        }
                    }
                } else if (downLoadInfo != null) { //旧资源
                    if (!new File(mainJsonPath).exists() || !new File(catalogueJsonPath).exists() || !new File(resourcePath).exists()//作业的那几个文件和文件夹都必须存在，不然就得重新下载，防止人为删除文件夹后点击无反映的问题。
                            || !(new File(resourcePath).list().length > 0)) {//lzh添加判断文件是否存在
                        downLoadWork(workContent, groupPosition, childPosition);
                    } else if (new File(mainJsonPath).exists() && new File(catalogueJsonPath).exists() && new File(resourcePath).exists()) { //下载的所有文件都必须没有丢失，否则就去下载
                        checkUpdateResourse(myWork, workContent, downLoadInfo, groupPosition, childPosition);//检查资源有没有更新
                    } else {
                        downLoadWork(workContent, groupPosition, childPosition);
                    }
                }
            }

        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }

    }

    //检查资源包是否有更新
    public void checkUpdateResourse(final MyWork myWork, final WorkContents workContent, final DownLoadInfo oldloadInfo, final int groupPosition, final int childPosition) {//检查离线包是否更新
        EpaperDao.getInstance().getCatalogueInfoNew(workContent.getPackageId(),
                workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId(), new BaseExtCallBack(EarlierHomeWorkActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                    @Override
                    public void success(Object data) {
                        try {
                            EpaperQRInfo info = (EpaperQRInfo) data;
                            if (oldloadInfo != null && info != null) {
                                if (!info.getHash().equals(oldloadInfo.getHash())) { //资源包有更新 删除本地文件  并且重新下载
                                    String path = "";
                                    if (oldloadInfo.getType() == 1) {//新资源
                                        path = ESystem.getPackagesCatalogueNew(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId());//资源包地址
                                    } else {//旧资源
                                        path = ESystem.getPackagesCatalogue(workContent.getPackageId(), workContent.getcId());//资源包地址
                                    }
//                                      FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST,"资源需要更新  YES", myWork.getWorkId());
                                    FileUtils.delete(path);
                                    downLoadWork(workContent, groupPosition, childPosition);//重新下载

                                } else {//没有更新   则走原来逻辑
                                    failed("没有更新");
//                                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_HOMEWORK_LIST,"资源不需要更新 NO",  myWork.getWorkId());
                                }

                            } else {
                                failed(data);//没有更新   则走原来逻辑
                            }
                        } catch (Exception e) {
                            e.getStackTrace();
                            hideDownloadProgress();
                        }
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        failed("检查更新失败");
                    }

                    @Override
                    public void failed(Object data) {
                        try {
                            hideDownloadProgress();
                            DownLoadInfo downLoadInfo = new DownLoadInfo();
                            if (oldloadInfo == null) {
                                downLoadInfo.setBookId(workContent.getPackageId());
                                downLoadInfo.setChapterId(workContent.getcId());
                                if (!TextUtils.isEmpty(workContent.resourceUrl)) {//新资源
                                    downLoadInfo.setType(1);
                                    downLoadInfo.setModuleId(workContent.getModuleId() + "");
                                    downLoadInfo.setVersionId(workContent.getVersionId());
                                }
                            } else {
                                downLoadInfo = oldloadInfo;
                            }
                            if (data instanceof String && data.toString().equals("检查更新失败")) {
                                localJumpAction(myWork, workContent, downLoadInfo, true);
                            } else {
                                localJumpAction(myWork, workContent, downLoadInfo, false);
                            }


                        } catch (Exception e) {
                            e.getStackTrace();
                            hideDownloadProgress();
                        }

                    }
                });
    }

    /**
     * 获取Module信息后跳转至做作业
     *
     * @param workContent
     * @param downLoadInfo
     */
    private void localJumpAction(final MyWork myWork,
                                 final WorkContents workContent, final DownLoadInfo downLoadInfo, final boolean isCheckUpdateFail) {
        try {
            String path = ESystem.getPackagesMainJsonPath(
                    workContent.getPackageId(), workContent.getcId());
            EpaperDao.getInstance().getSerializableObjects(path, Main.class,

                    new BaseExtCallBack(EarlierHomeWorkActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                        @Override
                        public void failed(Object data) {
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_EARLIER_HOMEWORK_LIST, "获取本地Main数据失败", "本地读取资源");
                            ToastUtil.INSTANCE.toastCenterError("获取本地Main数据失败");


                            //hideCricleProgress();
                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            //hideCricleProgress();
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_EARLIER_HOMEWORK_LIST, "获取本地Main数据失败", "本地读取资源");
                            ToastUtil.INSTANCE.toastCenterError("获取本地Main数据失败");
                            if (downLoadInfo.getStatus() != DownloadStatus.STATUS_UPZIPING) {
                                super.failed(errorCode, data);
                            }
                        }

                        @Override
                        public void success(Object data) {
                            Main main = (Main) data;
                            getCatalogueFile(myWork, workContent, downLoadInfo, main.getCatalogueFile(), main.getJsonVersion(), isCheckUpdateFail);
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }

    }

    /**
     * 获取目录内容信息
     *
     * @param workContent  目录内容信息地
     * @param downLoadInfo
     * @param path
     * @param jsonVersion
     */
    private void getCatalogueFile(final MyWork myWork, final WorkContents workContent, final DownLoadInfo downLoadInfo, String path, final String jsonVersion, final boolean isCheckUpdateFail) {
        try {
            path = ESystem.getPackagesPath(EarlierHomeWorkActivity.this) + File.separator + path;
            Type responseType = new TypeToken<List<Module>>() {
            }.getType();
            EpaperDao.getInstance().getSerializableObjects(path, responseType,

                    new BaseExtCallBack(EarlierHomeWorkActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


                        @Override
                        public void failed(Object data) {
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_EARLIER_HOMEWORK_LIST, "获取本地Modules失败", "本地读取资源");
                            ToastUtil.INSTANCE.toastCenterError("获取本地Modules失败");
                            //hideCricleProgress();
                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            //hideCricleProgress();
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_EARLIER_HOMEWORK_LIST, "获取本地Modules失败", "本地读取资源", true);

                            ToastUtil.INSTANCE.toastCenterError("获取本地Modules失败");
                            super.failed(errorCode, data);
                        }

                        @Override
                        public void success(Object data) {
                            try {
                                List<Module> modules = (List<Module>) data;
                                Module module = HomeWorkUtil.getModule(modules, workContent);

//                            saveLog(modules, module, workContent);
                                if (module == null) {
                                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_EARLIER_HOMEWORK_LIST, "解压后没有找到指定module", getRemarkNoFoundModule(workContent), true);
                                }
                                int index = HomeWorkUtil.getModuleContentIndex(module, workContent);
                                jumpToAction(myWork, workContent, downLoadInfo, module, index, jsonVersion, isCheckUpdateFail);
                            } catch (Exception e) {
                                e.getStackTrace();
                                hideDownloadProgress();
                            }
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }

    }


    /**
     * 跳转动作
     *
     * @param workContent
     * @param downLoadInfo
     * @param module
     * @param index
     * @param jsonVersion
     */
    private void jumpToAction(final MyWork myWork,
                              final WorkContents workContent, final DownLoadInfo downLoadInfo,
                              final Module module, final int index, final String jsonVersion, boolean isCheckUpdateFail) {
        CheckIsExamForDetail.INSTANCE.checkExamATime(myWork.getEffectiveDate(), workContent.getContentId() + "", workContent.getNowDate(), workContent.getExamMode(), workContent.getSeeWorkMode(), workContent.getSubmitMode());
        try {
            final int moduleId = workContent.getModuleId();
            ModuleContent moduleContent = module.getResourceList().get(index);
            downLoadInfo.mJsonResPath = ESystem.getPackagesJsonPath(moduleContent.getResourceFile());
            if (index <= -1 && moduleId != ModuleInfo.ModuleInfoId.MODULE_ID_TRAIN && moduleId != ModuleInfo.ModuleInfoId.MODULE_ID_TEST) {
                downLoadWork(workContent, -1, -1);

                if (isCheckUpdateFail) {
                    ToastUtil.INSTANCE.toastCenterError("检查更新失败，正在重新下载！");
                } else {
                    ToastUtil.INSTANCE.toastCenterError("获取资源失败，正在重新下载！");
                }

                hideCricleProgress();
                return;
            }

            // setWorkNotifyReadAction(myWork.workId);

            // 作业类型时文
            if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ESSAY) {
                MeJumpManager.jumpToTimeNewsH5Activity(R.string.go_back, EarlierHomeWorkActivity.this, downLoadInfo, module, index);

            }

            // 同步测试
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_TEST) {
                if (index > -1) {

                    String packagesJsonPath = ESystem.getPackagesJsonPath(module.getResourceList().get(index).getResourceFile());

                    if (new File(packagesJsonPath).exists()) {
                        EpaperJumpManager.jumpToDictaion(R.string.go_back, EarlierHomeWorkActivity.this, downLoadInfo, module, index);

                        return;
                    }
                }
                showToastSuccess(R.string.offline_answer);
            }
            // 同步跟读
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT) {
                if (DialogUtil.sdIsFull(downLoadInfo)) {
                    DialogUtil.showSdFullDialog(EarlierHomeWorkActivity.this);
                    return;
                }
                String resourceModuleId = module.getResourceList().get(index).getResourceType();
                String requirementContent = workContent.getRequirementContent();
                RequirementContent rc = null;
                if (!TextUtils.isEmpty(requirementContent)) {
                    rc = new Gson().fromJson(requirementContent,
                            RequirementContent.class);
                }
                if (rc == null) {
                    ChooseReadDialog dialog = new ChooseReadDialog(EarlierHomeWorkActivity.this,
                            myWork.workId, downLoadInfo, module, index, resourceModuleId,
                            RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.getServiceType(), myWork.classId, myWork.getEffectiveDate());
                    dialog.show();
                } else {
                    int speakType;
                    if (resourceModuleId.equals(ModuleContent.ResourceType.RESOURCE_TYPE_LESSON)) {
                        // 句子
                        switch (rc.getSpeekingtype()) {
                            case RequirementContent.SpeakType.SPEEK_TYPE_REPEAT:
                                speakType = SpeechPlayController.LISTENER_MODE_ZHUJU;
                                break;

                            case RequirementContent.SpeakType.SPEEK_TYPE_THROUGH:
                                speakType = SpeechPlayController.LISTENER_MODE_DULI;
                                break;

                            case RequirementContent.SpeakType.SPEEK_TYPE_RECITE:
                                speakType = SpeechPlayController.LISTENER_MODE_XUANDUAN;
                                break;
                            default:
                                speakType = SpeechPlayController.LISTENER_MODE_ZHUJU;
                                break;
                        }
                        EpaperJumpManager.jumpToSentenceRead(R.string.go_back, EarlierHomeWorkActivity.this, myWork.workId, downLoadInfo, module, rc,
                                index, speakType,
                                RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.getServiceType(), myWork.classId, workContent.contentId, workContent, myWork.getEffectiveDate());
                    } else { // 单词
                        switch (rc.getSpeekingtype()) {
                            case RequirementContent.SpeakType.SPEEK_TYPE_THROUGH:
                                speakType = SpeechUtils.WordReadMode.READ_THROUGH;
                                break;
                            default:
                                speakType = SpeechUtils.WordReadMode.READ_REPEAT;
                                break;
                        }

                        EpaperJumpManager.jumpToWordRead(R.string.go_back,
                                EarlierHomeWorkActivity.this, myWork.workId, downLoadInfo, module, rc, index, speakType,
                                RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.classId, workContent.getVersionId(), myWork.getServiceType(), false, workContent, myWork.getEffectiveDate());
                    }
                }
            }
            // 听说模考
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
                if (DialogUtil.sdIsFull(downLoadInfo)) {
                    DialogUtil.showSdFullDialog(EarlierHomeWorkActivity.this);
                    return;
                }
                EpaperJumpManager.jumpToListenSpeakWork(
                        R.string.go_back, EarlierHomeWorkActivity.this, myWork.workId,
                        downLoadInfo, module, index, myWork.classId, jsonVersion,
                        workContent.getCheckedResource(), ListenSpeakUtil.LsMode.HOME_WORK_MODE,
                        myWork.getServiceType(), workContent, 0, 0, false);
            }
            // 同步训练
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_TRAIN) {
                showToastSuccess(R.string.offline_answer);

            }
            // 报听写
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_DICTATION) {
                EpaperJumpManager.jumpToDictaionNew(R.string.go_back, EarlierHomeWorkActivity.this, myWork.workId, downLoadInfo, module, index, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.classId, workContent.getVersionId(), myWork.getServiceType(), false, workContent, myWork.getEffectiveDate());

            }
            // 视频讲解，h5 页面  123 or 126
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN_NEW) {
                ViedoJumpManager.jumpToNewVideoExplationActivity(R.string.go_back, EarlierHomeWorkActivity.this, downLoadInfo, module, index, workContent.getCommentContent(), workContent.getResourceName(), myWork.getServiceType(), null, null, myWork.classId);
            }
            // 在线作答
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {
                MeJumpManager.jumpToOnlineAnswerCordovaActivity(EarlierHomeWorkActivity.this, moduleContent, module, downLoadInfo, index, OnlineAnswerCordovaActivity.FROM_HOME_WORK, myWork.getWorkId(), myWork.getEffectiveDate(), workContent.contentId, 1, myWork.getServiceType(), workContent, 0);
            }
            // 互动教程
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_INTERACTIVE_TUTORIAL) {
                MeJumpManager.jumpToInteractiveTutorialCordovaActivity(EarlierHomeWorkActivity.this, moduleContent, module, downLoadInfo, index, myWork.getServiceType(), InteractiveTutorialCordovaActivity.FROM_HOME_WORK, myWork.getWorkId(), workContent.contentId, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK);
            }
            //试卷
            else {// 其它类型
                showToastError(R.string.no_support_work_type);

            }
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }


    }


    private void jumpToWork(final WorkContents workContent, final DownLoadInfo downLoadInfo, final MyWork myWork) {
        CheckIsExamForDetail.INSTANCE.checkExamATime(myWork.getEffectiveDate(), workContent.getContentId() + "", workContent.getNowDate(), workContent.getExamMode(), workContent.getSeeWorkMode(), workContent.getSubmitMode());
        try {
            int moduleId = workContent.getModuleId();
            //setWorkNotifyReadAction(myWork.workId);
            if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ESSAY) {
                downLoadInfo.setVersionId(workContent.getVersionId());
                MeJumpManager.jumpToTimeNewsH5Activity(R.string.go_back, EarlierHomeWorkActivity.this, downLoadInfo, null, 0);

            }  // 同步测试
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_TEST) {
                String packagesJsonPath = ESystem.getPackagesJsonPathNew(downLoadInfo.getBookId(), downLoadInfo.getChapterId(), downLoadInfo.getModuleId(), downLoadInfo.getVersionId());

                if (new File(packagesJsonPath).exists()) {
                    EpaperJumpManager.jumpToDictaion(R.string.go_back, EarlierHomeWorkActivity.this, downLoadInfo, null, 0);

                    return;
                }

                showToastSuccess(R.string.offline_answer);
            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_SENTENCE_REPEAT) {

                if (DialogUtil.sdIsFull(downLoadInfo)) {
                    DialogUtil.showSdFullDialog(EarlierHomeWorkActivity.this);
                    return;
                }
                String resourceModuleId = downLoadInfo.getResourceType();

                String requirementContent = workContent.getRequirementContent();
                RequirementContent rc = null;
                if (!TextUtils.isEmpty(requirementContent)) {
                    rc = new Gson().fromJson(requirementContent,
                            RequirementContent.class);
                }
                if (rc == null) {
                    ChooseReadDialog dialog = new ChooseReadDialog(EarlierHomeWorkActivity.this,
                            myWork.workId, downLoadInfo, null, 0, resourceModuleId,
                            RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.getServiceType(), myWork.classId, myWork.getEffectiveDate());
                    dialog.show();
                } else {
                    int speakType;
                    if (resourceModuleId.equals(ModuleContent.ResourceType.RESOURCE_TYPE_LESSON)) {
                        // 句子
                        switch (rc.getSpeekingtype()) {
                            case RequirementContent.SpeakType.SPEEK_TYPE_REPEAT:
                                speakType = SpeechPlayController.LISTENER_MODE_ZHUJU;
                                break;

                            case RequirementContent.SpeakType.SPEEK_TYPE_THROUGH:
                                speakType = SpeechPlayController.LISTENER_MODE_DULI;
                                break;

                            case RequirementContent.SpeakType.SPEEK_TYPE_RECITE:
                                speakType = SpeechPlayController.LISTENER_MODE_XUANDUAN;
                                break;
                            default:
                                speakType = SpeechPlayController.LISTENER_MODE_ZHUJU;
                                break;
                        }
                        EpaperJumpManager.jumpToSentenceRead(R.string.go_back, EarlierHomeWorkActivity.this, myWork.workId, downLoadInfo, null, rc,
                                0, speakType,
                                RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.getServiceType(), myWork.classId, workContent.contentId, workContent, myWork.getEffectiveDate());
                    } else { // 单词
                        switch (rc.getSpeekingtype()) {
                            case RequirementContent.SpeakType.SPEEK_TYPE_THROUGH:
                                speakType = SpeechUtils.WordReadMode.READ_THROUGH;
                                break;
                            default:
                                speakType = SpeechUtils.WordReadMode.READ_REPEAT;
                                break;
                        }

                        EpaperJumpManager.jumpToWordRead(R.string.go_back,
                                EarlierHomeWorkActivity.this, myWork.workId, downLoadInfo, null, rc, 0, speakType,
                                RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.classId, workContent.getVersionId(), myWork.getServiceType(), false, workContent, myWork.getEffectiveDate());
                    }
                }


            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
                if (DialogUtil.sdIsFull(downLoadInfo)) {
                    DialogUtil.showSdFullDialog(EarlierHomeWorkActivity.this);
                    return;
                }

                EpaperJumpManager.jumpToListenSpeakWorkNew(R.string.go_back,
                        EarlierHomeWorkActivity.this, false, myWork.getWorkId(), myWork.getEffectiveDate(), downLoadInfo, myWork.classId, workContent.getCheckedResource(), ListenSpeakUtil.LsMode.HOME_WORK_MODE, myWork.getServiceType(), workContent, 0, 0);

            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_DICTATION) {
                EpaperJumpManager.jumpToDictaionNew(R.string.go_back,
                        EarlierHomeWorkActivity.this, myWork.workId, downLoadInfo, null, 0,
                        RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, myWork.classId, workContent.getVersionId(), myWork.getServiceType(), false, workContent, myWork.getEffectiveDate());
            } // 视频讲解，h5 页面  123 or 126
            else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN_NEW) {
                ViedoJumpManager.jumpToNewVideoExplationActivity(R.string.go_back, EarlierHomeWorkActivity.this, downLoadInfo, null, 0, workContent.getCommentContent(), workContent.getResourceName(), myWork.getServiceType(), null, null, myWork.classId);


            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {
                MeJumpManager.jumpToOnlineAnswerCordovaActivity(EarlierHomeWorkActivity.this, null, null, downLoadInfo, 0, OnlineAnswerCordovaActivity.FROM_HOME_WORK, myWork.getWorkId(), myWork.getEffectiveDate(), workContent.contentId, 1, myWork.getServiceType(), workContent, 0);
            } else if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_SENTENCE_REPEAT) {

            }
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }

    }

    /**
     * 下载作业
     */
    private void downLoadWork(WorkContents workContents, int groupPosition, int childPosition) {
        try {
            showCancelButtonOfDownloadProgress();
            if (!NetworkUtils.isOnline()) {

            }
            DownLoadInfo tempInfo = new DownLoadInfo();
            tempInfo.setSavePath(DownLoad.getInstance()
                    .getDownloadPathById(workContents.getPackageId(),
                            workContents.getcId()));
            DownLoadInfo info = DownLoad.getInstance()
                    .getCurrentBean(tempInfo);

            // 不存在下载队列中添加到下载队列, 失败了重新请求地址重下
            if (info == null || info.getStatus() == DownloadStatus.STATUS_FAILED
                    || info.getStatus() == DownloadStatus.STATUS_FAILED_SDISFULL
                    || info.getStatus() == DownloadStatus.STATUS_FAILED_UNZIP) {
                //if (TextUtils.isEmpty(workContents.resourceUrl)) {//旧资源需要重新请求下载地址。
                getCatalogueInfoAction(workContents, workContents.getcId(), groupPosition, childPosition);

            } else {
                //解决 弱网情况下 下载没有回调问题，把任务挂起 后继续下载
                DownLoad.getInstance().pauseTask(info);
                DownLoad.getInstance().resumeTask(info);
//                toastInCenter("正在下载作业资源,请下载完成再打开作业！");
                // 下载状态
                switch (info.getStatus()) {
                    case DownloadStatus.STATUS_PAUSE:
                        DownLoad.getInstance().resumeTask(info);
                        break;
                    case DownloadStatus.STATUS_FAILED:
                    case DownloadStatus.STATUS_FAILED_SDISFULL:
                    case DownloadStatus.STATUS_FAILED_UNZIP:
                        DownLoad.getInstance().addTask(info);
                        break;
                    case DownloadStatus.STATUS_LOADING:
                    case DownloadStatus.STATUS_DOWNLOADING:
                        break;
                    case DownloadStatus.STATUS_UPZIPING:
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }


    }


    /**
     * 获取章节目录信息以及下载地址
     *
     * @param cId
     */
    private void getCatalogueInfoAction(final WorkContents workContents,
                                        final String cId, final int groupPosition, final int childPosition) {
        try {
            EpaperDao.getInstance().getCatalogueInfoNew(workContents.getPackageId(), cId, workContents.getModuleId() + "", workContents.getVersionId() + "",
                    new BaseExtCallBack(EarlierHomeWorkActivity.this) {

                        @Override
                        public void success(Object data) {
                            try {
                                EpaperQRInfo epaperQRInfo = (EpaperQRInfo) data;
                                String url = epaperQRInfo.getDownLoadUrl();

                                //测试地址  url="https://file.dzb.ciwong.com/epaper/20170912145905/catalogue_5238_6141001_v1505199545.res";


                                final DownLoadInfo downLoadInfo = new DownLoadInfo();
                                if (groupPosition != -1) {
                                    downLoadInfo.setSubjectId(myWorks.get(groupPosition).subjectId);
                                }
                                downLoadInfo.setType(epaperQRInfo.getcType());
                                downLoadInfo.setResourceName(workContents.getResourceName());
                                downLoadInfo.setResourceType(workContents.getResourceType());
                                downLoadInfo.setBookId(epaperQRInfo.getPackageId());
                                downLoadInfo.setBookName(epaperQRInfo.getPackageName());
                                downLoadInfo.setIconUrl(epaperQRInfo.getPackageCover());
                                downLoadInfo.setChapterId(epaperQRInfo.getcId());
                                downLoadInfo.setChapterName(epaperQRInfo.getcName());
                                downLoadInfo.setResourceName(workContents.getResourceName());
                                downLoadInfo.setResourceType(workContents.getResourceType());
                                //旧资源不用存moduleId 和versionId
                                downLoadInfo.setModuleId(workContents.getModuleId() + "");
                                downLoadInfo.setVersionId(workContents.getVersionId());
                                downLoadInfo.setUrl(url);

                                downLoadInfo.setSavePath(
                                        FileUtil.getSavePathByUrl(EarlierHomeWorkActivity.this, url));
                                downLoadInfo
                                        .setStatus(DownloadStatus.STATUS_LOADING);
                                downLoadInfo.setHash(epaperQRInfo.getHash());
                                String fileSize = epaperQRInfo.getFileSize();
                                downLoadInfo.groupPosition = groupPosition;
                                downLoadInfo.childPosition = childPosition;
                                if (!TextUtils.isEmpty(fileSize)
                                        && fileSize.contains(" ")) {
                                    downLoadInfo.setSize(fileSize.split(" ")[0]);
                                }

                                if (DialogUtil.sdIsFullForDownload(EarlierHomeWorkActivity.this, downLoadInfo)) {
                                    DialogUtil.showSdFullDialog(EarlierHomeWorkActivity.this,
                                            downLoadInfo.getSize());
                                    return;
                                }
                                if (NetworkUtils.isWifiOnline()) {
                                    DownLoad.getInstance()
                                            .addTask(downLoadInfo);

                                } else {
                                    hideDownloadProgress();
                                    DialogUtil.showWIFIDialog(
                                            EarlierHomeWorkActivity.this,
                                            downLoadInfo);
                                }

                            } catch (Exception e) {
                                e.getStackTrace();
                                hideDownloadProgress();
                            }

                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            hideDownloadProgress();
                            String errorMsg = data == null ? "" : data.toString();
                            String logDec = "packageId:" + workContents.getPackageId() + ",cId:" + cId + errorCode + ",errorMsg:" + errorMsg;
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_EARLIER_HOMEWORK_LIST, logDec, "获取章节目录信息以及下载地址失败" + getUrl());
                            ToastUtil.INSTANCE.toastCenterError("获取章节目录信息以及下载地址失败");

                        }

                        @Override
                        public void failed(Object data) {
                            hideDownloadProgress();

                            String errorMsg = data == null ? "" : data.toString();

                            String logDec = "packageId:" + workContents.getPackageId() + "mcId:" + cId + ",errorMsg:" + errorMsg;
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_EARLIER_HOMEWORK_LIST, logDec, "获取章节目录信息以及下载地址失败" + getUrl());
                            ToastUtil.INSTANCE.toastCenterError("获取章节目录信息以及下载地址失败");
                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }


    }

    /**
     * 下载完之后跳转作业方法
     */

    private void jumpToDoWorkAfterDownload(WorkContents workContent, MyWork myWork) {
        try {
            DownLoadInfo downLoadInfoNew = DownLoad.getInstance().isPackageExist_New(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId());
            DownLoadInfo downLoadInfo = DownLoad.getInstance().isPackageExist(workContent.getPackageId(), workContent.getcId());
            String mainJsonPath = ESystem.getPackagesMainJsonPath(workContent.getPackageId(), workContent.getcId());
            String catalogueJsonPath = ESystem.getPackagesCatalogueJsonPath(workContent.getPackageId(), workContent.getcId());
            String resourcePath = ESystem.getPackagesResourcePath(workContent.getPackageId(), workContent.getcId());

            //资源不存在,而且本地也没有，就去下载了
            if (downLoadInfoNew == null && downLoadInfo == null) {
                downLoadWork(workContent, -1, -1);
            } else {
                if (downLoadInfoNew != null) {
                    //新资源
                    File packagesCatalogueFile_New = new File(ESystem.getPackagesCatalogueNew(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId()));
                    File packagesCatalogueMediaFile_New = new File(ESystem.getPackagesMediaPath_New(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId()));

                    File packagesCatalogueResourceFile_New = new File(ESystem.getPackagesResourcePath_New(workContent.getPackageId(), workContent.getcId(), workContent.getModuleId() + "", workContent.getVersionId()));
                    if (ListenSpeakUtil.isOnLineAnswerOrListenSpeakOrInteractiveTutorial(workContent.getModuleId()) || workContent.workTag == 2) {//线上作答和试卷不验证media文件夹
                        if (packagesCatalogueFile_New.exists() && packagesCatalogueResourceFile_New.exists()) {
                            if (workContent.workTag == 2) {
                                hideDownloadProgress();
                            }
                            jumpToWork(workContent, downLoadInfoNew, myWork);
                        } else {
                            //防止下载的包结构有问题，这时应该取消弹框
                            hideDownloadProgress();
                        }
                    } else {//其他作业需要验证media文件夹

                        if (packagesCatalogueFile_New.exists() && packagesCatalogueMediaFile_New.exists() && packagesCatalogueResourceFile_New.exists()) {
                            if (!ListenSpeakUtil.isOnLineAnswerOrListenSpeakOrInteractiveTutorial(workContent.getModuleId())) {
                                hideDownloadProgress();
                            }
                            jumpToWork(workContent, downLoadInfoNew, myWork);
                        } else {
                            //防止下载的包结构有问题，这时应该取消弹框
                            hideDownloadProgress();
                        }
                    }

                } else if (downLoadInfo != null) {
                    //旧资源
                    if (new File(mainJsonPath).exists() && new File(catalogueJsonPath).exists() && new File(resourcePath).exists()) { //下载的所有文件都必须没有丢失，否则就去下载
                        localJumpAction(myWork, workContent, downLoadInfo, false);//
                    } else {
                        //防止下载的包结构有问题，这时应该取消弹框
                        hideDownloadProgress();
                    }
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }

    }

    @Override
    public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
        return true;
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        refreshNetData(false);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        refreshNetData(true);

    }

    //隐藏加载框
    public void onEventMainThread(HideDownloadDialogBean hideDownloadDialogBean) {
        hideDownloadProgress();
    }

    public void onEventMainThread(EventBusFactory.DownloadEvent item) {
        try {
            DownLoadInfo downLoadInfo = item.getInfo();
            mCurrentDownloadInfo = downLoadInfo;
            if (mCurrentDownloadInfo != null) {
                if (mCurrentDownloadInfo != null) {
                    if (mCurrentDownloadInfo.getStatus() == DownloadStatus.STATUS_FILE_DOWNLOAD) {
                        hideCancelButtonOfDownloadProgress();
                    } else if (mCurrentDownloadInfo.getStatus() == DownloadStatus.STATUS_COMPLETED) {
                        //线上作答要去检查html离线包，所以下载完成先不隐藏下载框

                        if (EarlierHomeWorkActivity.this != null && EarlierHomeWorkActivity.this instanceof BaseActivity) {
                            if (EarlierHomeWorkActivity.this.isTopActivity()) {
                                judgeDownloadInfoAndWorkContents(downLoadInfo, mCurrentWorkContents, mCurrentMyWork);
                            } else {
                                hideDownloadProgress();
                            }
                        } else {
                            hideDownloadProgress();
                        }

                    } else if (mCurrentDownloadInfo.getStatus() == DownloadStatus.STATUS_FAILED) {
                        ToastUtil.INSTANCE.toastCenterError(R.string.download_fail);
                        hideDownloadProgress();
                    } else if (mCurrentDownloadInfo.getStatus() == DownloadStatus.STATUS_FAILED_SDISFULL) {
                        ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_sdfull_and_retry);
                        hideDownloadProgress();
                    } else if (mCurrentDownloadInfo.getStatus() == DownloadStatus.STATUS_FAILED_UNZIP) {
                        ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_unzip_and_retry);
                        hideDownloadProgress();
                    }
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }


    }

    private void judgeDownloadInfoAndWorkContents(DownLoadInfo downLoadInfo, WorkContents currentWorkContents, MyWork currentMyWork) {
        if (downLoadInfo.getBookId().equals(currentWorkContents.getPackageId()) && downLoadInfo.getChapterId().equals(currentWorkContents.getcId())) {
            //防止取消了仍会打开
            if (isDownloadProgressBarShowing()) {
                if (ListenSpeakUtil.isOnLineAnswerOrListenSpeakOrInteractiveTutorial(currentWorkContents.getModuleId())) {

                } else {
                    hideDownloadProgress();
                }
            }
            if (downLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
                //如果是新包还需要对比ModuleId和VersionId
                if (downLoadInfo.getModuleId().equals(currentWorkContents.getModuleId() + "") && downLoadInfo.getVersionId().equals(currentWorkContents.getVersionId())) {
                    jumpToDoWorkAfterDownload(currentWorkContents, currentMyWork);
                } else {
                    hideDownloadProgress();
                }
            } else {
                //如果是旧包只需要对比PackageId和ChapterId
                jumpToDoWorkAfterDownload(currentWorkContents, currentMyWork);
            }

        } else {
            hideDownloadProgress();
        }
    }

    public boolean isDownloadProgressBarShowing() {
        if (mDownloadProgressBar != null) {
            return mDownloadProgressBar.isShowing();
        }
        return false;
    }

    private String getRemarkNoFoundModule(WorkContents workContent) {
        return workContent.getcId() + "_" + workContent.getPackageId() + "  " + workContent.getResourceName();
    }
}
